/**********************************************************************
 Copyright (C) 2009 Jaakko Vuori

 This file is part of FlexiWorker.
 For more information, see <http://code.google.com/p/flexi-worker/>

 FlexiWorker is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 3 of the License, or
 (at your option) any later version.

 FlexiWorker is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with FlexiWorker.  If not, see <http://www.gnu.org/licenses/>.
 **********************************************************************/

#include "presencelogmodel.h"
#include <QDir>
#include <QDebug>

PresenceLogModel::PresenceLogModel()
{
    LogParser p(*this);

    QString testLogFile = QDir::toNativeSeparators("../viewer/test/test_log.log");
    if (QFile::exists(testLogFile))
    {
        p.parse(testLogFile);
    }
    else
    {
        p.parse(QDir(QDir::home().absoluteFilePath(".flexi-worker")).absoluteFilePath("flexi-worker.log"));
    }
}

void PresenceLogModel::newDay(const QDate& date)
{
    m_currentDate = date;
}

void PresenceLogModel::newEntry(const QDateTime& startTime, const QDateTime& endTime)
{
    qDebug() << "PresenceLogModel::newEntry" << startTime << endTime;
    TimeFrame e;
    e.m_startTime = startTime;
    e.m_endTime = endTime;
    if (m_currentDate.isNull())
    {
        m_currentDate = startTime.date();
    }
    m_entries[m_currentDate].append(e);
}

QList<TimeFrame> PresenceLogModel::presenceTimes(const QDate& date) const
{
    return m_entries[date];
}

QList<TimeFrame> PresenceLogModel::workingTimes(const QDate& date) const
{
    qDebug() << "PresenceLogModel::workingTimes" << date;
    if (m_adjustedWorkTimes.contains(date))
    {

        return m_adjustedWorkTimes[date];
    }
    else
    {
        QList<TimeFrame> workingTimes;
        if (m_entries[date].count() > 0)
        {
            TimeFrame w;
            w.m_startTime = m_entries[date][0].m_startTime;
            w.m_endTime = m_entries[date][m_entries[date].count() - 1].m_endTime;
            if (!w.m_startTime.isNull() && !w.m_endTime.isNull())
            {
                workingTimes.append(w);
            }
        }

        foreach (TimeFrame t, workingTimes)
        {
            qDebug() << t.m_startTime << t.m_endTime;
        }

        return workingTimes;
    }
}

void PresenceLogModel::updateWorkingTime(QDate date, int index, TimeFrame workingTime)
{
    if (m_adjustedWorkTimes.contains(date))
    {
        m_adjustedWorkTimes[date][index] = workingTime;
    }
    else
    {
        m_adjustedWorkTimes[date].append(workingTime);
    }
}
